<template>
  <div class="app-container">
    <el-card>
      <el-row>
        <p class="pinformation">搜索条件</p>
      </el-row>
      <el-form ref="queryRef" label-width="80" :model="queryParams">
        <el-row>
          <el-col :span="5">
            <el-form-item label="检测类别：" prop="jclbName">
              <el-input clearable maxlength="100" placeholder="请输入检测类别" v-model="queryParams.jclbName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="检测项目：" prop="jcxmName">
              <el-input clearable maxlength="100" placeholder="请输入检测项目" v-model="queryParams.jcxmName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="方法编号：" prop="methodCode">
              <el-input clearable maxlength="100" placeholder="请输入方法编号" v-model="queryParams.methodCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="方法名称：" prop="methodName">
              <el-input clearable maxlength="100" placeholder="请输入方法名称" v-model="queryParams.methodName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="center">
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation" style="margin-top: 8.5px">数据列表</p>
        <p class="totalStyle" style="margin-top: 6px">共 {{ total }} 条数据</p>
        <p class="totalStyle" style="margin-top: 6px">检测项目总数：{{ priceCountForm.jcxmCount }}</p>
        <p class="totalStyle" style="margin-top: 6px">检测方法总数：{{ priceCountForm.methodCount }}</p>
        <el-row style=" margin-left: 20px">
          <el-button link type="success" @click="handleExport">导出数据</el-button>
          <el-button link type="success" @click="handleImport">导入数据</el-button>
        </el-row>
      </el-row>
      <el-row justify="end">
        <span style="font-size: 14px">单位：元</span>
      </el-row>
      <el-table ref="mainTableRef" :data="priceList" v-loading="loading">
        <el-table-column label="序号" width="70" align="center">
          <template #default="scope">
            {{
              (queryParams.pageNum - 1) * queryParams.pageSize +
              scope.$index +
              1
            }}
          </template>
        </el-table-column>
        <el-table-column label="检测类别" prop="jclbName" align="center" />
        <el-table-column label="检测项目" prop="jcxmName" align="center">
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="方法编号" prop="methodCode" align="center" />
        <el-table-column label="方法名称" prop="methodName" align="center" width="550" />
        <el-table-column label="采样单价" prop="cyPrice" align="center">
          <template #default="scope">
            <el-input clearable maxlength="100" v-model="scope.row.cyPrice"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
              @blur="scope.row.cyPrice = $event.target.value" @change="submit(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="分析单价" prop="analysePrice" align="center">
          <template #default="scope">
            <el-input clearable maxlength="100" v-model="scope.row.analysePrice"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
              @blur="scope.row.analysePrice = $event.target.value" @change="submit(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="其他单价" prop="otherPrice" align="center">
          <template #default="scope">
            <el-input clearable maxlength="100" v-model="scope.row.otherPrice"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
              @blur="scope.row.otherPrice = $event.target.value" @change="submit(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="合计单价" prop="sumPrice" align="center" />
        <el-table-column label="备注" prop="priceDesc" align="center">
          <template #default="scope">
            <el-input clearable maxlength="500" v-model="scope.row.priceDesc" @change="submit(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 用户导入对话框 -->
    <el-dialog :class="'el-dialog-theme3'" :title="upload.title" v-model="upload.open" width="400px"
      append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleUploadError"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleExport">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PriceConfig">
import { getToken } from "@/utils/auth";
import {
  listPriceConfig,
  priceConfigCount,
  priceConfigSave,
} from "@/api/system/priceConfig";
const { proxy } = getCurrentInstance();
const queryParams = ref({ pageNum: 1, pageSize: 10 });
const priceCountForm = ref({});
const total = ref(0);
const priceList = ref([]);
const loading = ref(false);

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function getList() {
  loading.value = true;
  listPriceConfig(queryParams.value).then((res) => {
    priceList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

priceConfigCount().then((res) => {
  priceCountForm.value = res.data;
});

function submit(row) {
  priceConfigSave(row).then(() => {
    proxy.$modal.msgSuccess("保存成功");
    getList();
  });
}

getList();

// ---------------------表格自适应高度-----------------------
watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 73 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
})

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
// -------------------导入模板逻辑-------------------
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/lims/priceConfig/importData",
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "检测项目价格导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("lims/priceConfig/export", {
    ...queryParams.value,
  }, `检测项目方法价格表_${new Date().getTime()}.xlsx`);
};

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}
</script>

<style></style>
